package com.qf.controller;

import com.qf.mapper.TicketMapper;
import com.qf.pojo.Ticket;
import com.qf.utils.ThreadUtiils;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.spring.boot.CuratorZkTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private TicketMapper ticketMapper;

    @Value("${winnum}")
    private Integer winnum;

    @Autowired
    private CuratorZkTemplate curatorZkTemplate;

    public static final String LOCK_PREFIX = "/LOCK:";


    @GetMapping("/sell/{id}")
    public void sell(@PathVariable("id") Integer id){
        while (true){

            //添加分布式锁
            InterProcessLock lock = curatorZkTemplate.getSharedReentrantLock(LOCK_PREFIX + id);

            try {
                //加锁
                lock.acquire();

                Ticket ticket = ticketMapper.selectById(id);

                if (ticket.getCount() > 0) {
                    System.out.println(winnum + "号窗口正在卖出第：" + ticket.getCount() + "张票");

                    //模拟卖票的时间
                    ThreadUtiils.sleep(1000);

                    //更新票数
                    int count = ticket.getCount() - 1;
                    ticket.setCount(count);
                    //更新数据库
                    ticketMapper.updateById(ticket);

                    System.out.println(winnum + "号窗口剩余票数为：" + count);
                } else {
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //释放锁
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
